home *** CD-ROM | disk | FTP | other *** search
/ Total Network Tools 2002 / NextStepPublishing-TotalNetworkTools2002-Win95.iso / Archive / Misc Servers / Zope.exe / WIN32EVTLOGUTIL.PY < prev    next >
Encoding:
Python Source  |  1999-01-27  |  5.6 KB  |  142 lines

  1. """Event Log Utilities - helper for win32evtlog.pyd
  2. """
  3.  
  4. import win32api, win32con, winerror, win32evtlog, string
  5.  
  6. error = win32api.error # The error the evtlog module raises.
  7.  
  8. langid = win32api.MAKELANGID(win32con.LANG_ENGLISH, win32con.SUBLANG_ENGLISH_US)
  9.  
  10. def AddSourceToRegistry(appName, msgDLL, eventLogType = "Application"):
  11.   """Add a source of messages to the event log.
  12.  
  13.   Allows Python program to register a custom source of messages in the
  14.   registry.  You must also provide the DLL name that has the message table, so the
  15.   full message text appears in the event log.
  16.  
  17.   Note that the win32evtlog.pyd file has a number of string entries with just "%1"
  18.   built in, so many Python programs can simply use this DLL.  Disadvantages are that
  19.   you do not get language translation, and the full text is stored in the event log,
  20.   blowing the size of the log up.
  21.   """
  22.   
  23.   # When an application uses the RegisterEventSource or OpenEventLog
  24.   # function to get a handle of an event log, the event loggging service
  25.   # searches for the specified source name in the registry. You can add a
  26.   # new source name to the registry by opening a new registry subkey
  27.   # under the Application key and adding registry values to the new
  28.   # subkey. 
  29.  
  30.   # Create a new key for our application 
  31.   hkey = win32api.RegCreateKey(win32con.HKEY_LOCAL_MACHINE, \
  32.       "SYSTEM\\CurrentControlSet\\Services\\EventLog\\%s\\%s" % (eventLogType, appName))
  33.  
  34.   # Add the Event-ID message-file name to the subkey.
  35.   win32api.RegSetValueEx(hkey, 
  36.       "EventMessageFile",    # value name \
  37.       0,                     # reserved \
  38.       win32con.REG_EXPAND_SZ,# value type \
  39.       msgDLL)
  40.  
  41.   # Set the supported types flags and add it to the subkey.
  42.   data = win32evtlog.EVENTLOG_ERROR_TYPE | win32evtlog.EVENTLOG_WARNING_TYPE | win32evtlog.EVENTLOG_INFORMATION_TYPE
  43.   win32api.RegSetValueEx(hkey, # subkey handle \
  44.       "TypesSupported",        # value name \
  45.       0,                       # reserved \
  46.       win32con.REG_DWORD,      # value type \
  47.       data)
  48.   win32api.RegCloseKey(hkey)
  49.  
  50. def RemoveSourceFromRegistry(appName, eventLogType = "Application"):
  51.   """Removes a source of messages from the event log.
  52.   """
  53.   
  54.   # Delete our key 
  55.   try:
  56.     win32api.RegDeleteKey(win32con.HKEY_LOCAL_MACHINE, \
  57.                  "SYSTEM\\CurrentControlSet\\Services\\EventLog\\%s\\%s" % (eventLogType, appName))
  58.   except win32api.error, (hr, fn, desc):
  59.       if hr != ERROR_FILE_NOT_FOUND:
  60.           raise
  61.    
  62.  
  63.  
  64. def ReportEvent(appName, eventID, eventCategory = 0, eventType=win32evtlog.EVENTLOG_ERROR_TYPE, strings = None, data = None, sid=None):
  65.   """Report an event for a previously added event source.
  66.   """
  67.     
  68.   # Get a handle to the Application event log 
  69.   hAppLog = win32evtlog.RegisterEventSource(None, appName)
  70.  
  71.   # Now report the event, which will add this event to the event log */
  72.   win32evtlog.ReportEvent(hAppLog, # event-log handle \
  73.       eventType,
  74.       eventCategory,
  75.       eventID,
  76.       sid,
  77.       strings,
  78.       data)
  79.  
  80.   win32evtlog.DeregisterEventSource(hAppLog);
  81.  
  82. def FormatMessage( eventLogRecord, logType="Application" ):
  83.     """Given a tuple from ReadEventLog, and optionally where the event
  84.     record came from, load the message, and process message inserts.
  85.  
  86.     Note that this function may raise win32api.error.  See also the
  87.     function SafeFormatMessage which will return None if the message can
  88.     not be processed.
  89.     """
  90.     
  91.     # From the event log source name, we know the name of the registry
  92.     # key to look under for the name of the message DLL that contains
  93.     # the messages we need to extract with FormatMessage. So first get
  94.     # the event log source name...
  95.     keyName = "SYSTEM\\CurrentControlSet\\Services\\EventLog\\%s\\%s" % (logType, eventLogRecord.SourceName)
  96.  
  97.     # Now open this key and get the EventMessageFile value, which is
  98.     # the name of the message DLL.
  99.     handle = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, keyName)
  100.     try:
  101.         dllName = win32api.RegQueryValueEx(handle, "EventMessageFile")[0]
  102.         # Expand environment variable strings in the message DLL path name,
  103.         # in case any are there.
  104.         dllName = win32api.ExpandEnvironmentStrings(dllName)
  105.     
  106.         dllHandle = win32api.LoadLibraryEx(dllName, 0, win32con.DONT_RESOLVE_DLL_REFERENCES)
  107.         try:
  108.             data = win32api.FormatMessageW(win32con.FORMAT_MESSAGE_FROM_HMODULE, 
  109.                     dllHandle, eventLogRecord.EventID, langid, eventLogRecord.StringInserts)
  110.         finally:
  111.             win32api.FreeLibrary(dllHandle)
  112.     finally:
  113.         win32api.RegCloseKey(handle)
  114.     return data
  115.  
  116. def SafeFormatMessage( eventLogRecord, logType=None ):
  117.     """As for FormatMessage, except returns an error message if
  118.     the message can not be processed.
  119.     """
  120.     if logType is None: logType = "Application"
  121.     try:
  122.         return FormatMessage(eventLogRecord, logType)
  123.     except win32api.error:
  124.         if eventLogRecord.StringInserts is None:
  125.             desc = ""
  126.         else:
  127.             desc = string.join(map(lambda x:str(x), eventLogRecord.StringInserts), ", ")
  128.         return "<The description for Event ID ( %d ) in Source ( %s ) could not be found. It contains the following insertion string(s):%s.>" % (winerror.HRESULT_CODE(eventLogRecord.EventID), eventLogRecord.SourceName, desc)
  129.  
  130. def FeedEventLogRecords(feeder, machineName = None, logName = "Application", readFlags = None):
  131.     if readFlags is None:
  132.         readFlags = win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ
  133.  
  134.     h=win32evtlog.OpenEventLog(machineName, logName)
  135.     try:
  136.         while 1:
  137.             objects = win32evtlog.ReadEventLog(h, readFlags, 0)
  138.             if not objects:
  139.                 break
  140.             map(lambda item, feeder = feeder: apply(feeder, (item,)), objects)
  141.     finally:
  142.         win32evtlog.CloseEventLog(h)